

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { CollectionItem, CategoryFilter, TypeFilter, SortFilter } from './types';
import Header from '../../components/Header';

const UserCollectionsPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [collectionSearchKeyword, setCollectionSearchKeyword] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<CategoryFilter>('');
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('');
  const [sortFilter, setSortFilter] = useState<SortFilter>('collect_time');
  const [currentPage, setCurrentPage] = useState(1);

  // 收藏数据
  const [collectionsData, setCollectionsData] = useState<CollectionItem[]>([
    {
      id: 'content1',
      title: '批判性思维：如何建立理性思考框架',
      description: '掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。',
      author: '李教授',
      publishDate: '2024-01-15',
      collectTime: '2024-01-20',
      category: 'cognition',
      type: 'article',
      imageUrl: 'https://s.coze.cn/image/dFClcM5mOiQ/'
    },
    {
      id: 'content2',
      title: '30天全身训练计划：从零开始塑造完美身材',
      description: '科学的训练计划，适合初学者的全身锻炼方案，帮助你建立运动习惯。',
      author: '健身教练王老师',
      publishDate: '2024-01-12',
      collectTime: '2024-01-18',
      category: 'fitness',
      type: 'video',
      imageUrl: 'https://s.coze.cn/image/LegUak9sqXU/'
    },
    {
      id: 'content3',
      title: '费曼学习法：如何快速掌握新知识',
      description: '通过费曼技巧，学会用简单的语言解释复杂概念，加深理解和记忆。',
      author: '学习专家张老师',
      publishDate: '2024-01-10',
      collectTime: '2024-01-16',
      category: 'learning',
      type: 'article',
      imageUrl: 'https://s.coze.cn/image/9bN8aUJ1p14/'
    },
    {
      id: 'content4',
      title: '第一性原理：从根本上解决问题的思维方法',
      description: '深度解析埃隆·马斯克的思维模式，学会从本质出发思考问题。',
      author: '思维教练刘老师',
      publishDate: '2024-01-08',
      collectTime: '2024-01-14',
      category: 'cognition',
      type: 'video',
      imageUrl: 'https://s.coze.cn/image/tInxahGHgCo/'
    },
    {
      id: 'content5',
      title: 'HIIT高强度间歇训练的科学原理与实践',
      description: '了解HIIT训练的生理机制，制定高效的燃脂计划和训练方案。',
      author: '运动生理学陈老师',
      publishDate: '2024-01-05',
      collectTime: '2024-01-12',
      category: 'fitness',
      type: 'article',
      imageUrl: 'https://s.coze.cn/image/3PAtwavOjNE/'
    },
    {
      id: 'content6',
      title: '番茄工作法：提升专注力的实用时间管理技巧',
      description: '掌握时间管理的核心方法，告别拖延症，提高工作和学习效率。',
      author: '效率专家周老师',
      publishDate: '2024-01-03',
      collectTime: '2024-01-10',
      category: 'learning',
      type: 'video',
      imageUrl: 'https://s.coze.cn/image/WcQsxN8BxCU/'
    }
  ]);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '我的收藏 - 精进坊';
    return () => { document.title = originalTitle; };
  }, []);

  // 筛选和搜索逻辑
  const filteredCollections = collectionsData.filter(item => {
    // 搜索筛选
    const matchesSearch = collectionSearchKeyword === '' || 
      item.title.toLowerCase().includes(collectionSearchKeyword.toLowerCase()) ||
      item.description.toLowerCase().includes(collectionSearchKeyword.toLowerCase());
    
    // 分类筛选
    const matchesCategory = categoryFilter === '' || item.category === categoryFilter;
    
    // 类型筛选
    const matchesType = typeFilter === '' || item.type === typeFilter;
    
    return matchesSearch && matchesCategory && matchesType;
  });

  // 排序逻辑
  const sortedCollections = [...filteredCollections].sort((a, b) => {
    switch (sortFilter) {
      case 'title':
        return a.title.localeCompare(b.title);
      case 'publish_date':
        return new Date(b.publishDate).getTime() - new Date(a.publishDate).getTime();
      case 'collect_time':
      default:
        return new Date(b.collectTime).getTime() - new Date(a.collectTime).getTime();
    }
  });

  // 取消收藏处理
  const handleUncollect = (contentId: string) => {
    if (confirm('确定要取消收藏这个内容吗？')) {
      setCollectionsData(prev => prev.filter(item => item.id !== contentId));
    }
  };

  // 内容卡片点击处理
  const handleContentClick = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}`);
  };

  // 分页处理
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 分类标签样式映射
  const getCategoryStyle = (category: string) => {
    switch (category) {
      case 'cognition':
        return 'bg-secondary text-white';
      case 'fitness':
        return 'bg-green-500 text-white';
      case 'learning':
        return 'bg-purple-500 text-white';
      default:
        return 'bg-secondary text-white';
    }
  };

  // 分类文本映射
  const getCategoryText = (category: string) => {
    switch (category) {
      case 'cognition':
        return '认知提升';
      case 'fitness':
        return '身体健身';
      case 'learning':
        return '学习能力';
      default:
        return '认知提升';
    }
  };

  // 类型标签样式映射
  const getTypeStyle = (type: string) => {
    switch (type) {
      case 'article':
        return 'bg-primary text-secondary';
      case 'video':
        return 'bg-green-100 text-green-600';
      default:
        return 'bg-primary text-secondary';
    }
  };

  // 类型文本映射
  const getTypeText = (type: string) => {
    switch (type) {
      case 'article':
        return '文章';
      case 'video':
        return '视频';
      default:
        return '文章';
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 头部栏 */}
      <Header currentPage="" />

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">我的收藏</h2>
                <nav className="text-sm text-text-secondary">
                  <Link to="/home" className="hover:text-secondary">首页</Link>
                  <span className="mx-2">/</span>
                  <Link to="/user-profile" className="hover:text-secondary">个人中心</Link>
                  <span className="mx-2">/</span>
                  <span>我的收藏</span>
                </nav>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-secondary">{sortedCollections.length}</div>
                <div className="text-sm text-text-secondary">总收藏数</div>
              </div>
            </div>
          </div>

          {/* 工具栏区域 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-4 mb-6`}>
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
              {/* 搜索框 */}
              <div className="flex-1 max-w-md">
                <div className="relative">
                  <input 
                    type="text" 
                    placeholder="搜索收藏内容..." 
                    value={collectionSearchKeyword}
                    onChange={(e) => setCollectionSearchKeyword(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  />
                  <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
              </div>
              
              {/* 筛选和排序 */}
              <div className="flex flex-wrap items-center space-x-3">
                {/* 分类筛选 */}
                <div className="relative">
                  <select 
                    value={categoryFilter}
                    onChange={(e) => setCategoryFilter(e.target.value as CategoryFilter)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 text-sm focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="">全部分类</option>
                    <option value="cognition">认知提升</option>
                    <option value="fitness">身体健身</option>
                    <option value="learning">学习能力</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
                
                {/* 内容类型筛选 */}
                <div className="relative">
                  <select 
                    value={typeFilter}
                    onChange={(e) => setTypeFilter(e.target.value as TypeFilter)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 text-sm focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="">全部类型</option>
                    <option value="article">文章</option>
                    <option value="video">视频</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
                
                {/* 排序 */}
                <div className="relative">
                  <select 
                    value={sortFilter}
                    onChange={(e) => setSortFilter(e.target.value as SortFilter)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 text-sm focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="collect_time">收藏时间</option>
                    <option value="publish_date">最新发布</option>
                    <option value="title">标题</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
              </div>
            </div>
          </div>

          {/* 内容展示区域 */}
          <div className="mb-8">
            <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
              {sortedCollections.map((item) => (
                <div 
                  key={item.id}
                  className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}
                  onClick={() => handleContentClick(item.id)}
                >
                  <div className="relative">
                    <img 
                      src={item.imageUrl} 
                      alt={`${item.title}封面`} 
                      className="w-full h-48 object-cover rounded-t-card"
                    />
                    <div className={`absolute top-3 left-3 ${getCategoryStyle(item.category)} px-2 py-1 rounded-full text-xs font-medium`}>
                      {getCategoryText(item.category)}
                    </div>
                    <div className="absolute top-3 right-3">
                      <button 
                        className="w-8 h-8 bg-white bg-opacity-90 rounded-full flex items-center justify-center text-gray-600 hover:text-red-500 hover:bg-white transition-colors"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleUncollect(item.id);
                        }}
                      >
                        <i className="fas fa-heart text-sm"></i>
                      </button>
                    </div>
                  </div>
                  <div className="p-5">
                    <h4 className="font-semibold text-text-primary mb-2 line-clamp-2">{item.title}</h4>
                    <p className="text-text-secondary text-sm mb-4 line-clamp-2">{item.description}</p>
                    <div className="flex items-center justify-between text-xs text-text-secondary mb-3">
                      <span><i className="fas fa-user mr-1"></i>{item.author}</span>
                      <span><i className="fas fa-calendar mr-1"></i>{item.publishDate}</span>
                    </div>
                    <div className="flex items-center justify-between text-xs text-text-secondary">
                      <span><i className="fas fa-clock mr-1"></i>收藏于 {item.collectTime}</span>
                      <span className={`${getTypeStyle(item.type)} px-2 py-1 rounded-full`}>{getTypeText(item.type)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 分页区域 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-4`}>
            <div className="flex items-center justify-between">
              <div className="text-sm text-text-secondary">
                显示第 <span className="font-medium">1-{sortedCollections.length}</span> 条，共 <span className="font-medium">{sortedCollections.length}</span> 条收藏
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  className="px-3 py-2 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" 
                  disabled={currentPage === 1}
                  onClick={() => handlePageChange(currentPage - 1)}
                >
                  <i className="fas fa-chevron-left mr-1"></i>上一页
                </button>
                
                <div className="flex space-x-1">
                  <button 
                    className={`px-3 py-2 text-sm rounded-lg ${currentPage === 1 ? styles.paginationActive : 'hover:bg-gray-50'}`}
                    onClick={() => handlePageChange(1)}
                  >
                    1
                  </button>
                  <button 
                    className={`px-3 py-2 text-sm rounded-lg ${currentPage === 2 ? styles.paginationActive : 'hover:bg-gray-50'}`}
                    onClick={() => handlePageChange(2)}
                  >
                    2
                  </button>
                  <button 
                    className={`px-3 py-2 text-sm rounded-lg ${currentPage === 3 ? styles.paginationActive : 'hover:bg-gray-50'}`}
                    onClick={() => handlePageChange(3)}
                  >
                    3
                  </button>
                  <span className="px-3 py-2 text-sm text-text-secondary">...</span>
                  <button 
                    className={`px-3 py-2 text-sm rounded-lg ${currentPage === 5 ? styles.paginationActive : 'hover:bg-gray-50'}`}
                    onClick={() => handlePageChange(5)}
                  >
                    5
                  </button>
                </div>
                
                <button 
                  className="px-3 py-2 text-sm border border-gray-200 rounded-lg hover:bg-gray-50"
                  onClick={() => handlePageChange(currentPage + 1)}
                >
                  下一页<i className="fas fa-chevron-right ml-1"></i>
                </button>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

export default UserCollectionsPage;

